<template>
  <div class="professor-dashboard">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1>研究生奖学金管理系统 - 导师端</h1>
          <div class="user-info">
            <span>欢迎，{{ tutorName }}</span>
            <el-button link @click="logout">退出登录</el-button>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="250px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="dashboard">
              <el-icon><DataBoard /></el-icon>
              <span>仪表板</span>
            </el-menu-item>
            <el-menu-item index="review-applications">
              <el-icon><Document /></el-icon>
              <span>审核申请</span>
            </el-menu-item>
            <el-menu-item index="scoreboard">
              <el-icon><Trophy /></el-icon>
              <span>奖学金排名</span>
            </el-menu-item>
            <el-menu-item index="course-score-management">
              <el-icon><Edit /></el-icon>
              <span>成绩管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <div class="dashboard-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-number">{{ stats.pendingCount }}</div>
                    <div class="stat-label">待审核申请</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-number">{{ stats.approvedCount }}</div>
                    <div class="stat-label">已通过申请</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-number">{{ stats.rejectedCount }}</div>
                    <div class="stat-label">已拒绝申请</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <el-card class="recent-applications">
              <template #header>
                <span>最近申请</span>
              </template>
              <div v-if="loading" class="loading-container">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>加载中...</span>
              </div>
              <div v-else-if="error" class="error-container">
                <el-alert :title="error" type="error" show-icon />
              </div>
              <el-table v-else :data="recentApplications" style="width: 100%">
                <el-table-column prop="studentName" label="学生姓名" />
                <el-table-column prop="scholarshipName" label="奖学金名称" />
                <el-table-column prop="applyTime" label="申请时间" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { DataBoard, Document, Trophy, Edit, Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const activeMenu = ref('dashboard')
const tutorName = ref(localStorage.getItem('name') || '导师')
const loading = ref(false)
const error = ref('')

const stats = ref({
  pendingCount: 0,
  approvedCount: 0,
  rejectedCount: 0
})

const recentApplications = ref([])

const handleMenuSelect = (index) => {
  if (index === 'dashboard') {
    router.push('/professor/dashboard')
  } else if (index === 'review-applications') {
    router.push('/professor/review-applications')
  } else if (index === 'scoreboard') {
    router.push('/professor/scoreboard')
  } else if (index === 'course-score-management') {
    router.push('/professor/course-score-management')
  }
}

const logout = () => {
  localStorage.clear()
  router.push('/login')
}

const getStatusType = (status) => {
  switch (status) {
    case 'pending':
    case '申请中':
      return 'warning'
    case 'approved':
    case '已通过':
      return 'success'
    case 'rejected':
    case '已拒绝':
      return 'danger'
    default:
      return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'pending':
    case '申请中':
      return '待审核'
    case 'approved':
    case '已通过':
      return '已通过'
    case 'rejected':
    case '已拒绝':
      return '已拒绝'
    default:
      return '未知'
  }
}

const loadDashboardData = async () => {
  loading.value = true
  error.value = ''
  
  try {
    console.log('开始加载仪表板数据...')
    
    // 获取统计数据
    console.log('获取统计数据...')
    const statsResponse = await axios.get('/scholarship-applications/stats')
    console.log('统计数据响应:', statsResponse.data)
    stats.value = statsResponse.data
    
    // 获取最近申请
    console.log('获取最近申请...')
    const recentResponse = await axios.get('/scholarship-applications/recent')
    console.log('最近申请响应:', recentResponse.data)
    
    // 获取学生列表和奖学金列表用于数据转换
    console.log('获取学生和奖学金列表...')
    const [studentsResponse, scholarshipsResponse] = await Promise.all([
      axios.get('/students'),
      axios.get('/scholarships')
    ])
    
    const students = studentsResponse.data
    const scholarships = scholarshipsResponse.data
    
    console.log('学生列表:', students)
    console.log('奖学金列表:', scholarships)
    
    // 处理最近申请数据，添加学生姓名和奖学金名称
    recentApplications.value = recentResponse.data.map(app => {
      const student = students.find(s => s.studentId === app.studentId)
      const scholarship = scholarships.find(s => s.scholarshipId === app.scholarshipId)
      
      return {
        ...app,
        studentName: student ? student.name : app.studentId,
        scholarshipName: scholarship ? scholarship.name : app.scholarshipId,
        applyTime: app.applyDate ? new Date(app.applyDate).toLocaleDateString('zh-CN') : ''
      }
    })
    
    console.log('处理后的最近申请数据:', recentApplications.value)
    
  } catch (err) {
    console.error('加载仪表板数据失败:', err)
    error.value = '加载数据失败，请稍后重试'
    
    // 如果API调用失败，使用默认数据
    stats.value = {
      pendingCount: 0,
      approvedCount: 0,
      rejectedCount: 0
    }
    recentApplications.value = []
    
    ElMessage.error('加载数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  console.log('导师仪表板页面已挂载')
  loadDashboardData()
})
</script>

<style scoped>
.professor-dashboard {
  height: 100vh;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.sidebar {
  background: #f5f7fa;
  border-right: 1px solid #e6e6e6;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
  background: #f0f2f5;
}

.dashboard-content {
  max-width: 1200px;
  margin: 0 auto;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.recent-applications {
  margin-top: 20px;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  gap: 10px;
  color: #666;
}

.error-container {
  padding: 20px;
}
</style> 